﻿using System.Collections.Generic;
using System.Threading;

namespace AdvancedMap
{
    class QueuedSounds
    {
        private System.Media.SoundPlayer myPlayer;

        EventWaitHandle wh = new AutoResetEvent (false);
        Thread worker;
        object locker = new object();
        Queue<string> tasks = new Queue<string>();
         
        public QueuedSounds()
        {
            worker = new Thread (Work);
            myPlayer = new System.Media.SoundPlayer();
            worker.Start();
        }
         
        public void EnqueueTask (string task) 
        {
            if (!tasks.Contains(task))  // don't requeue existing sounds
            {
                lock (locker) tasks.Enqueue(task);
                wh.Set();
            }
        }
         
        public void Dispose()
        {
            EnqueueTask (null);     // Signal the consumer to exit.
            worker.Join();          // Wait for the consumer's thread to finish.
            wh.Close();             // Release any OS resources.
        }
         
        void Work()
        {
            while (true) {
              string task = null;
              lock (locker)
                if (tasks.Count > 0)
                {
 //                   task = tasks.Dequeue();       // Moved this to after sound plays
                    task = tasks.Peek();            // Keep sound in queue to minimize duplicates
                    if (task == null) return;
                }
              if (task != null) 
              {
                  if (Map.MyAM.playSound)
                  {
                      myPlayer.SoundLocation = task;
                      myPlayer.PlaySync();
                      Thread.Sleep(250);
                  }
                  task = tasks.Dequeue();
              }
              else
                wh.WaitOne();         // No more tasks - wait for a signal
            }
        }

    }
}
